import React, { useCallback, useEffect, useState } from 'react';
import {getInfo,deleInfo,addInfo,updateInfo} from '@/api/api.js'
// import useFun from '@/hooks/UseFun';
const FetchApi = () => {
  const [stuData, setStuData] = useState([])
  const [loading, setLoading] = useState(false)
  // 获取
  const fetchData = async () => {
    let data = await getInfo()
    setLoading(false)
    setStuData(data.data)
  }
  // let {data, testFun} = useFun()
  // console.log('data',data)
  // console.log('testFun',testFun())
  useEffect(()=>{
    setLoading(true)
    fetchData()
  },[])
  // console.log('stuData',stuData)
  // 删除
  const deleData = async(id) => {
    let result = await deleInfo(id)
    console.log('result',result)
    fetchData()
  }
  // 修改
  const [values, setValues] = useState({
    nameInp: "",
    ageInp: '',
    sexInp: "",
    addressInp: "",
  })
  const changeHandler = (e) => {
    const {name, value } = e.target
    setValues({
      ...values,
      [name]: value
    })
  }
  const [id, setId] = useState(null)
  const editShow = (id,item) => {
    setId(id)
    setValues({
      ...values,
      nameInp: item.name,
      ageInp: item.age,
      sexInp: item.sex,
      addressInp: item.address
    })
  }
  const editData = async() => {
    let params = {
      name: values.nameInp,
      age: +values.ageInp,
      sex: values.sexInp,
      address: values.addressInp
    }
    let result = await updateInfo(id,params)
    setValues({
      nameInp: '',
      ageInp: '',
      sexInp: '',
      addressInp: '',
    })
    fetchData()
  }
  // 添加
  const saveData = useCallback(async() => {
    let params = {
      name: values.nameInp,
      age: +values.ageInp,
      sex: values.sexInp,
      address: values.addressInp
    }
    let data = await addInfo(params)
    fetchData()
  },[values])
  const DOM = stuData.map(p => <div key={p.id}>
    <span>{p.attributes.name}，</span>
    <span>{p.attributes.age}，</span>
    <span>{p.attributes.sex}，</span>
    <span>{p.attributes.address}</span>
    <span onClick={()=>{deleData(p.id)}} style={{margin:"10px",cursor:'pointer'}}>删除</span>
    <span onClick={()=>{editShow(p.id, p.attributes)}} style={{cursor:'pointer'}}>编辑</span>
  </div>)
  return (
    <>
      <h2>FetchApi</h2>
      {!loading && DOM}
      {loading && <p>数据正在加载。。。</p>}
      <span>姓名</span><input type="text" name='nameInp' onChange={changeHandler} value={values.nameInp} /> <br/>
      <span>年龄</span><input type="number" name='ageInp' onChange={changeHandler} value={values.ageInp}/> <br/>
      <span>性别</span><input type="text" name='sexInp' onChange={changeHandler} value={values.sexInp}/> <br/>
      <span>地址</span><input type="text" name='addressInp' onChange={changeHandler} value={values.addressInp}/> <br/>
      <button onClick={saveData}>添加</button>
      <button onClick={editData}>确认修改</button>
    </>
  );
};
export default FetchApi;